<template>
  <div :class="['json-editor', {'is-look': isLook}]">
    <textarea ref="textarea" />
  </div>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'

import 'codemirror/theme/eclipse.css'
import 'codemirror/theme/ayu-dark.css'


require('script-loader!jsonlint')
import 'codemirror/mode/javascript/javascript'
import 'codemirror/mode/python/python'
import 'codemirror/mode/shell/shell'
import 'codemirror/mode/yaml/yaml'
import 'codemirror/mode/css/css'
import 'codemirror/mode/markdown/markdown'
import 'codemirror/mode/dockerfile/dockerfile'


import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'

export default {
  name: 'JsonEditor',
  /* eslint-disable vue/require-prop-types */
  props: ['value', 'mode', 'isLook'],
  data () {
    return {
      jsonEditor: false
    }
  },
  watch: {
    value (value) {
      const editorValue = this.jsonEditor.getValue()
      if (value !== editorValue) {
        this.jsonEditor.setValue(this.value)
        // this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
      }
    }
  },
  mounted () {
    let deploy = {}
    if (this.isLook) {
      deploy = {
        mode: this.mode,
        gutters: [],
        theme: `${this.$IsDarkHue ? 'ayu-dark': 'eclipse'}`,
        readOnly: 'nocursor'
      }
    } else {
      deploy = {
        lineNumbers: true,
        mode: this.mode,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter", "CodeMirror-lint-markers"],
        theme: `${this.$IsDarkHue ? 'ayu-dark': 'eclipse'}`,
        foldGutter: true, // 启用行槽中的代码折叠
        autofocus: true, // 自动聚焦
        matchBrackets: true, // 匹配结束符号，比如"]、}"
        autoCloseBrackets: true, // 自动闭合符号
        styleActiveLine: true, // 显示选中行的样式
        lint: true,
      }
    }
    console.log(deploy)
    this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, deploy)

    this.jsonEditor.setValue(this.value)
    this.jsonEditor.on('change', cm => {
      this.$emit('changed', cm.getValue())
      this.$emit('input', cm.getValue())
    })
  },
  methods: {
    getValue () {
      return this.jsonEditor.getValue()
    }
  }
}
</script>

<style scoped>
.json-editor {
  height: 100%;
  position: relative;
}
.json-editor >>> .CodeMirror {
  height: 100%;
  /* min-height: 300px; */
}
.json-editor >>> .CodeMirror-scroll {
  height: 100%;
}
.json-editor >>> .cm-s-rubyblue span.cm-string {
  color: #f08047;
}
.is-look {
  padding: 40px;
  width: 100%;
  box-sizing: border-box;
}
</style>